<?php
class NewsController extends Controller
{
	public function filters()
	{
		return array(
            'accessControl',
		);
	}
	public function accessRules()
	{
		return array(
		array('allow',
	                'actions'=>array('index','list','view','category','reply'),
	                'users'=>array('*'),
		),
		array('allow',
			        'actions'=>array('user'),
			        'users'=>array('@'),
		),
		array('allow',
	                'actions'=>array('new','add', 'delete','admin','postadmin','postsave'),
	                'users'=>array("ilookadmin","gaopengfei"),
		),
		array('deny',
	                'users'=>array('*'),
		),
		);
	}
	//首页-》转到List默认页
	public function actionIndex()
	{
		$this->redirect("List",array("id"=>'1'));
	}
	//新闻分类列表
	public function actionCategory()
	{
		$this->pageTitle = "掌上新闻-iLook";
		$this->pageDescription="iLook新加坡,新加坡华语新闻网,新加坡掌上资讯,新加坡华文资讯";
		$this->pageKeywords="iLook新加坡,国际观察,社会热点,大千世界,娱乐八卦,科技之光,";
		$newsies = NewsCategory::model()->findAll("parent_id=1 order by hits desc");
		$this->render("category",array("newsies"=>$newsies));
	}
	//新闻列表
	public function actionList($id=1){
		$news = $this->loadByPk($id);
		//列表点击+1
		$news->hits++;
		$news->save();

		$this->pageTitle="掌上新闻-{$news->title}";
		$this->pageDescription="iLook新加坡,新加坡华语新闻网,新加坡掌上资讯,新加坡华文资讯,$this->pageTitle";
		$this->pageKeywords = "iLook新加坡,新加坡华语新闻网,新加坡掌上资讯,新加坡华文资讯,$this->pageTitle";

		$criteria = new CDbCriteria;
		$criteria -> order ='flag desc,id desc';
		if($id !=1){
			$criteria -> condition = "category_id=$id and (flag='active' or flag = 'featured' )";
		}else{
			//默认页不现实【秘密花园】的新闻
			$criteria -> condition = "category_id!='2' and (flag='active' or flag = 'featured' )";
		}
		$pages = new CPagination(NewsTopic::model() -> count($criteria));
		$pages -> pageSize =20;
		$pages -> applyLimit($criteria);		
		$topics = NewsTopic::model()->findAll($criteria);
		
		$this->render('list',array(
			'news'=>$news,
			'topics'=>$topics,
			'pages'=>$pages,
		));
	}
	//查看新闻内容
	public function actionView($id){
		$topic = $this->loadTopicByPk($id);
		//新闻点击+1
		$topic->hits++;
		$tpic->post='0';
		$topic->save();
		//新闻评论
		if(isset($_POST['NewsPost'])){
			$post= new NewsPost();
			$post->attributes = $_POST['NewsPost'];
			$post->content = strip_tags($post->content);
			if(!Yii::app()->user->isGuest){
				$post->member_id = Yii::app()->user->id;
				if(UserIdentity::getUserDetail(Yii::app()->user->id)->nickname==null){
					$member = Member::model()->findByPk(Yii::app()->user->id);
					$post->author = $member->username;
				}else{
					$post->author = UserIdentity::getUserDetail(Yii::app()->user->id)->nickname;
				}
				
			}else{
				$post->author = $_SERVER['REMOTE_ADDR'];
			}
			$post->save();
			//回复+1
			$topic->comments++;
			$topic->save();
		}
		
		$news = $this->loadByPk($topic->category_id);
		$this->pageTitle="{$news->title}-{$topic->title}";
		$this->pageDescription=$this->pageTitle;
		$this->pageKeywords = $this->pageTitle;
		
		$criteria = new CDbCriteria;
		$criteria -> order ='created';
		$criteria -> condition = "topic_id=$id";
		$pages = new CPagination(NewsPost::model() -> count($criteria));
		$pages -> pageSize =20;
		$pages -> applyLimit($criteria);
		$posts = NewsPost::model()->findAll($criteria);
		
		$this->render('view',array(
					'news'=>$news,
					'topic'=>$topic,
					'pages'=>$pages,
					'posts'=>$posts,
		));	
	}
	//发新闻
	public function actionNew($id){
		$news = $this->loadByPk($id);
		//发布
		if(isset($_POST['NewsPost'])){
			$post= new NewsPost();
			$post->attributes = $_POST['NewsPost'];
			if(!empty($post->title) && strlen($post->content)>10){
				$post->member_id = Yii::app()->user->id;
				$member = Member::model()->findByPk(Yii::app()->user->id);
				if(UserIdentity::getUserDetail(Yii::app()->user->id)->nickname==null){
					$post->author = $member->username;
				}else{
					$post->author = UserIdentity::getUserDetail(Yii::app()->user->id)->nickname;
				}			
				$topic = new NewsTopic();
				$topic->title = $post->title;
				$topic->category_id = $news->id;
				$topic->category = $news->title;
				$topic->member_id = Yii::app()->user->id;
				if(UserIdentity::getUserDetail(Yii::app()->user->id)->nickname==null){
					$topic->author = $member->username;
				}else{
					$topic->author = UserIdentity::getUserDetail(Yii::app()->user->id)->nickname;
				}
				$topic->author = $member->username;
				$topic->flag = 'active';
				$topic->save();
				$post->topic_id = $topic->id;
				$post->save();
					
				$this->redirect(array("news/view","id"=>"$topic->id"));
			}
			else {
				$this->render('new',array(
									'news'=>$news,
									'post'=>$post,
									'error'=>'您提交的内容不符合论坛要求，标题为必填，内容不能少于10个字！',
				));
			}
		}
		else if($news->id!=1){
			$post = new NewsPost();
			$this->render('new',array(
					'news'=>$news,
					'post'=>$post,
			));	
		}
		else{
			$this->redirect(array("site/page","view"=>"error"));
		}
	}
	//引用评论-》发评论
	public function actionReply($id,$title=null,$post_id=null){
		$topic = $this->loadTopicByPk($id);
		//必须回复某个楼层
		if(!empty($post_id)){
			$re_post = $this->loadPostByPk($post_id);
			if(isset($_POST['NewsPost'])){
				$post= new NewsPost();
				$post->attributes = $_POST['NewsPost'];
				if(strlen($post->content)>10){
					$post->content = "<div class='tie-reference'>".$title.$re_post->content."<br/></div>"."回复".$title." ".strip_tags($post->content);
					if(!Yii::app()->user->isGuest){
						$post->member_id = Yii::app()->user->id;
						$member = Member::model()->findByPk(Yii::app()->user->id);
						if(UserIdentity::getUserDetail(Yii::app()->user->id)->nickname==null){
							$post->author = $member->username;
						}else{
							$post->author = UserIdentity::getUserDetail(Yii::app()->user->id)->nickname;
						}
					}else{
						$post->author = $_SERVER['REMOTE_ADDR'];
					}
					$post->topic_id = $topic->id;
					$post->save();
					$topic->comments++;
					$topic->save();
					$this->redirect(array("news/view","id"=>"$topic->id"));
				}
				else {
					$this->render('reply',array(
						'topic'=>$topic,
						'title'=>$title,
						'post'=>$post,
						're_post'=>$re_post,
						'post_id'=>$post_id,
						'error'=>'您提交的内容不符合要求，内容不能少于5个字！',
					));
				}
			}
			else{
				$post = new NewsPost();
				$post->title =$title;
				$this->render('reply',array(
						'topic'=>$topic,
						'title'=>$title,				
						're_post'=>$re_post,
						'post_id'=>$post_id,
						'post'=>$post,
				));
			}
		}else{
			$this->redirect(array("site/page","view"=>"error"));
		}
	}
	//新闻分类编辑
	public function actionAdmin($id=1){
		if(isset($_POST["NewsCategory"])){
			foreach($_POST["NewsCategory"] as $NewsArr){
				$news = NewsCategory::model()->findByPk($NewsArr['id']);
				$news->attributes=$NewsArr;
				$image_file=CUploadedFile::getInstanceByName("NewsCategory[$news->id][image_file]");
				if($news->save()){
					if(!empty($image_file)){
						$file = Yii::app()->basePath."/../images/news/{$news->id}.png";
						$image_file->saveAs("$file");
					}
				}
			}
		}
		$newsies = NewsCategory::model()->findAll("parent_id=$id");
		$curr_news = $id!=0? NewsCategory::model()->findByPk($id):null;
		$this->render('admin',array("newsies"=>$newsies,"curr_news"=>$curr_news));
	}
	//添加分类
	public function actionAdd($id){
		$news = new NewsCategory;
		$news->parent_id=$id;
		$news->title="未命名";
		$news->save();
		$this->redirect(array("news/admin","id"=>$id));
	}
	//删除分类
	public function actionDelete($id){
		$news = NewsCategory::model()->findByPk($id);
		$parent_id = $news->parent_id;
		if(NewsCategory::model()->count("parent_id=$id")!=0 ||NewsTopic::model()->count("category_id=$id")!=0){
			Yii::app()->user->setFlash('failure','操作失败，你必须先删除该列表下地所有子类和新闻！');
		}else{
			$file = Yii::app()->basePath."/../images/news/{$news->id}.png";
			if(is_file($file)){
				unlink($file);
			}
			$news->delete();
		}
		$this->redirect(array("news/admin","id"=>$parent_id));
	}
	//新闻后台
	public function actionPostadmin($id=null){
 		if(empty($id)){
 			$this->render('postadmin');
 		}
		else{
		$topic= NewsTopic::model()->findByPK($id);
			if (isset($topic)){
				if(isset($_GET['delete'])){
					//删除此新闻
					NewsPost::model()->deleteAll("topic_id=$topic->id");
					$topic->delete();
					$info = "帖子删除成功！";
					$this->render('postadmin',array(
											'id'=>$topic->id,
											'info'=>$info,
					));
				}
				$info=null;
				if(isset($_GET['edit'])){
					//edit posts
					$news =  $this->loadByPk($_GET['NewsTopic']['category_id']);
					$topic->category_id = $news->id;
					$topic->category=$news->title;
					$topic->title=$_GET['NewsTopic']['title'];
					if ($_GET['NewsTopic']['featured']==1){
						$topic->flag='featured';
					}else{
						$topic->flag='active';
					}
					$topic->save();
					$info ='主题编辑成功';
				}
				
				$criteria = new CDbCriteria;
				$criteria -> order ='id desc';
				$criteria -> condition = "topic_id=$topic->id";
				$pages = new CPagination(NewsPost::model() -> count($criteria));
				$pages -> pageSize =20;
				$pages -> applyLimit($criteria);
				$posts = NewsPost::model()->findAll($criteria);
				
				$this->render('postadmin',array(
						'id'=>$topic->id,
						'topic'=>$topic,
						'posts'=>$posts,
						'info'=>$info,
						'pages'=>$pages,
				));		
			}else{
				$error = "您搜索的帖子不存在！";
				$this->render('postadmin',array(
						'error'=>$error,
				));
			}
		}
	}
	//新闻内容-评论编辑
	public function actionPostsave(){
		$topic= $this->loadTopicByPk($_POST['id']);
		if(isset($_POST['save'])){
			//edit posts
			$posts = $_POST['NewsPost'];
			foreach($posts as $post){
				$post2 = NewsPost::model()->findByPK($post['id']);
				$post2->title =$post['title'];
				$post2->content=$post['content'];
				$post2->flag=$post['hide']==1?"inactive":"active";
				$post2->save();
			}
			$info ='帖子编辑成功';
		}

		$criteria = new CDbCriteria;
		$criteria -> order ='id';
		
		$criteria -> condition = "topic_id=$topic->id";
		$pages = new CPagination(NewsPost::model() -> count($criteria));
		$pages -> pageSize =20;
		$pages -> applyLimit($criteria);
		$posts = NewsPost::model()->findAll($criteria);

		$this->render('postadmin',array(
							'id'=>$topic->id,
							'topic'=>$topic,
							'posts'=>$posts,
							'info'=>$info,
							'pages'=>$pages,
		));
	}
	public function actionUser($id=null){
		if (empty($id)){
			$posts = NewsPost::model()->findAll("member_id=".Yii::app()->user->id." order by id desc limit 20");
			$this->render("user",array("posts"=>$posts));
		}
		else{
			$member = $this->getUserByPK($id);
			$posts = NewsPost::model()->findAll("member_id=".$id." order by id desc limit 20");	
			$this->render("user",array("posts"=>$posts,'id'=>$id,'username'=>$member->username,));
		}
	}

	private function loadByPk($pk){
		$model = NewsCategory::model()->findByPk($pk);
		if(isset($model)){
			return $model;
		}else{
			$this->redirect(array("site/page","view"=>"error"));
		}
	}
	private function getUserByPK($pk){
		$model = Member::model()->findByPk($pk);
		if(isset($model)){
			return $model;
		}else{
			$this->redirect(array("site/page","view"=>"error"));
		}
	}
	private function loadTopicByPk($pk){
		$model = NewsTopic::model()->findByPk($pk);
		if(isset($model)){
			return $model;
		}else{
			$this->redirect(array("site/page","view"=>"error"));
		}
	}
	private function loadPostByPk($pk){
		$model = NewsPost::model()->findByPk($pk);
		if(isset($model)){
			return $model;
		}else{
			$this->redirect(array("site/page","view"=>"error"));
		}
	}
}